package sample.asphalt2.control
{
	import asphalt2.Session;
	import asphalt2.action.$Action;
	import asphalt2.action.error.AlertErroDisplay;
	import asphalt2.action.error.TooltipErrorDisplay;
	import asphalt2.control.AbstractControl;
	import asphalt2.util.Async;
	import asphalt2.validator.IValidateError;
	import asphalt2.validator.ValidateError;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.controls.Alert;
	
	import sample.asphalt2.model.Employee;
	import sample.asphalt2.page.LoginPage;
	import sample.asphalt2.page.MainFramePage;
	
	public class LoginControl extends AbstractControl
	{
		public var page:LoginPage;
		
		override public function setup():void{

			var errorDisplay:TooltipErrorDisplay = new TooltipErrorDisplay();
			
			var alert:AlertErroDisplay = new AlertErroDisplay(3);
			
			var handler:Function = new $Action().errorDisplay(alert).validate(asyncValidate).
						success(storeToSession).nextPage(MainFramePage).createHandler();

			page.loginButton.addEventListener(
				MouseEvent.CLICK,handler); 
				
		}
		public function asyncValidate(async:Async):void{
		
			var id:String = page.userIdTextInput.text;
			var password:String = page.passwordTextInput.text;
			var error:IValidateError = new ValidateError();
			if(id == null || id == ""){
				error.addError("IDを入力してください", page.userIdTextInput);
			}
			if(password == null || password == ""){
				error.addError("パスワードを入力してください。", page.passwordTextInput);
			}
			
			if(error.isError()){
				async.gotoNext(error);
			}else{
				Alert.show("asyncValidate OK","async",Alert.OK,null,function():void{
					async.gotoNext(null);
				});
			}
		}
		public function storeToSession():void{
			var emp:Employee = new Employee();
			emp.id = page.userIdTextInput.text;
			var ses:Session = Session.session;
			ses.setAttribute("employee",emp);		
		}
		/*
		override public function validate():IValidateError{
			var page:LoginPage = LoginPage(UI);
			var id:String = page.userIdTextInput.text;
			var password:String = page.passwordTextInput.text;
			if((id == null || id == "") || (password == null || password == ""))
			{
				var error:IValidateError = new ValidateError();
				error.addError("id/password required", page.userIdTextInput);
				return error;
			}
			return null;
		}
		*/
		public function execute(e:Event):void
		{
		}
		
		public function finalize():void{}
	}
}